using System.Web.Mvc;
using CultivJupiterContactForm.Classes;
using CultivJupiterContactForm.Model;
using CultivJupiterContactForm.ViewModel;
using Umbraco.Cms.Web.Surface;

namespace CultivJupiterContactForm.Controllers
{
    [Surface("BB45D8A4-DD88-444E-89A6-A64351EFBE6A")]
    public class ContactFormSurfaceController : SurfaceController
    {
        private const string FormSentKey = "ContactFormSent";

        [ChildActionOnly]
        public PartialViewResult ContactForm()
        {
            var model = new ContactViewModel();

            var formSent = TempData[FormSentKey];
            if (formSent != null && bool.Parse(formSent.ToString()))
                model.SubmitHandled = true;

            return PartialView(model);
        }

        [HttpPost]
        public ActionResult HandleContactFormSubmit(ContactViewModel model)
        {
            // The "Other" field should be an empty string, this is a simple spam filter
            // based on: http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx
            // Had to use Request as model binding will say model.Other is null
            if (ModelState.IsValid && Request["Other"] == string.Empty)
            {
                var contact = new Contact
                {
                    Name = model.Name,
                    From = model.Email,
                    Message = model.Message,
                    Subject = "Contact mail from {0}"
                };

                new Email().Send(contact);

                TempData[FormSentKey] = true;
            }
            else
            {
                return CurrentUmbracoPage();
            }

            return RedirectToCurrentUmbracoPage();
        }
    }
}